import React, { Component } from 'react';
import { Tabs, Table, Select, Button,Row,Col ,Spin} from 'antd';
import * as fetch from '../../utils/http'
import moment from 'moment';
import ReactEchars from '../now-data/now-data-echars';
import Test from '../now-data/now-test';
const { Option } = Select;
const { TabPane } = Tabs;
const columns = [
    {
        title: '标签名',
        dataIndex: 'signNo',
        key: 'signNo',
        render: text => <b>{text}</b>,
    },
    {
        title: '标签编号',
        dataIndex: 'tag',
        key: 'tag',
    },
    {
        title: '日期',
        dataIndex: 'time',
        key: 'time',
    },
    {
        title: '当前值',
        dataIndex: 'value',
        key: 'value',
    }
];



class NowDataPage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            devices: [],
            tags: [],
            chartTags: [],
            isLoading: true,
            isChanging: true,
            deviceDefaultSelectValue: "",
            legendData:[],
            chartXData: [],
            chartYData: []
        }
        this.getDevices();
        this.startDataTimer();
    }


    //#region  list数据
    getDevices() {
        fetch.get('RealTime/GetDevicesForApp').then(res => {
            this.setState({
                devices: res.data || [],
                
                deviceDefaultSelectValue: res.data[0].id,
            });
            this.getDeviceTags();
            //顺便把图表的也请求了
            this.getDeviceChartTag();
        })
    }

    getDeviceTags() {
        const deviceId = this.state.deviceDefaultSelectValue;
        fetch.get('RealTime/GetDeviceTags?deviceID=' + deviceId).then(res => {
            var data = res.data;
            var items = data.deviceItems;
            if (!!items && items.length > 0) {
                var deviceItemProperties = items.map(function (item) {
                    return item.deviceItemProperties;
                });
                if (!!deviceItemProperties && deviceItemProperties.length > 0) {
                    const allTags = [];
                    var pros=deviceItemProperties.map(function (item) {
                        var proItem=item.map(function (it) {
                            if (!!it.tag) {
                                allTags.push(it.tag);
                            }
                        });
                    });
                    this.setState({
                        tags: allTags
                    });
                    this.getData();

                }
            }

        })
    }

    getData() {
        let tag = this.state.tags.join("|");
        fetch.get('RealTime/GetRealTimeDataByMoreSteps?tags=' + tag).then(res => {
            this.setState({
                data: res.data || [],
                isChanging: false
            })
        })
    }

    startDataTimer() {
        this.getDataTimerID = setInterval(
            () => {
                if (!this.state.isChanging && !this.state.isLoading) {
                    this.getData();
                }
            },
            5000
        );

    }

    clearDataTimer() {
        clearInterval(this.getDataTimerID);
    }

    componentWillUnmount() {
        if (!!this.getDataTimerID) {
            clearInterval(this.getDataTimerID);
        }
    }

    //#endregion


    //#region  chars数据

    getDeviceChartTag() {
        const deviceId = this.state.deviceDefaultSelectValue;
        fetch.get('History/GetChartTags?deviceID=' + deviceId).then(res => {
            var data = res.data || [];
            var allTagName = [];
            if (data.length > 0) {
                var tags = data.map((item) => {
                    if (!!item.tag) {
                        allTagName.push(item.tagChartName);
                        return item.tag;
                    }
                });
                this.setState({
                    chartTags: tags,
                    legendData: allTagName//多少条曲线
                });
                this.getChartFirstData();
            }
        })
    }

    //第一次获取半个小时的数据
    getChartFirstData() {
        const tag = this.state.chartTags.join("|");
        if(!tag){
            console.log("tag请求失败");
            return;
        }
        const now = moment();
        const endTime = now.format('YYYY-MM-DD HH:mm:ss')
        const startTime = now.subtract(2, 'hours').format('YYYY-MM-DD HH:mm:ss')
        fetch.get('History/GetHistoryDataByMoreSteps?tags=' + tag + "&startTime=" + startTime + "&endTime=" + endTime).then(res => {
            var data = res.data || [];
            if (data.length > 0) {
                //组装数据
                var first = data[0];
                var firstTag = first.tag;
                var firstData = data.filter(function (item) {
                    if (item.tag == firstTag) {
                        return item.time;
                    }
                });
                //x轴数据
                var timeData = firstData.map((item) => {
                    return item.time;
                })
                //有多少条曲线
                var allTags = this.state.legendData;
                var allValues = [];
                allTags.map((item) => {
                    var tagValue=data.filter(function(d){
                        return d.tagChartName==item;
                    });
                    var lowAxis = tagValue[0].lowAxis;
                    var highAxis = tagValue[0].highAxis;
                    allValues.push({
                        name: item,
                        value: tagValue.map((item)=>{
                            return item.value;
                        }),
                        lowAxis: lowAxis,
                        highAxis: highAxis
                    })
                });
                this.setState({
                    chartXData: timeData,
                    chartYData: allValues,
                    isLoading: false,
                })
            }
        })
    }

    //#endregion
    render() {
        const handleChange = (deviceId) => {
            this.setState({
                deviceDefaultSelectValue: deviceId,
                isChanging: true
            })
            this.getDeviceTags();
        }

        const handleChartChange = (deviceId) => {
            this.setState({
                deviceDefaultSelectValue: deviceId,
            });
            //
        }
        const refreshData = () => {
            this.getData();
            this.setState({
                isChanging: true
            })
        }

        const callback = (key) => {
            if (key == 1) {
                this.startDataTimer();
                // this.clearChartTimer();

            } else {
                this.clearDataTimer();
                // this.startChartTimer();
            }
        }

        if (this.state.isLoading) {
            return (<div style={{ textAlign: 'center', height: 460 }}><Spin style={{ marginTop: '15%' }} /></div>);
        } else {
            const deviceList = this.state.devices.map((d) =>
                <Option key={d.id} value={d.id}>{d.name}</Option>
            );
            return (
                <div>
                    <h3>实时数据</h3>
                    <Tabs
                        onChange={callback}
                        type="card"
                        bordered
                    >
                        <TabPane tab="实时数据" key="1">
                            <Select defaultValue={this.state.deviceDefaultSelectValue} style={{ width: 120 }} onChange={handleChange} >
                                {deviceList}
                            </Select>
                            <Button type="primary" onClick={refreshData} style={{ margin: 10 }}>刷新最新数据</Button>
                            <Table columns={columns} dataSource={this.state.data} rowKey="tag" loading={this.state.isChanging} />
                        </TabPane>
                        <TabPane tab="实时图表" key="2">
                            <Select defaultValue={this.state.deviceDefaultSelectValue} style={{ width: 120 }} onChange={handleChartChange} >
                                {deviceList}
                            </Select>
                            <ReactEchars legendData={this.state.legendData} chartXData={this.state.chartXData} chartYData={this.state.chartYData} chartTags={this.state.chartTags}></ReactEchars>
                            {/* <Test/> */}
                        </TabPane>
                    </Tabs>
                </div>
            );
        }

    }
}

export default NowDataPage;